<?php

namespace tools;

class Http
{

    //请求类型
    protected $type = 'POST';

    //请求url
    protected $url = "";

    //请求参数
    protected $data = [];

    //请求头设置
    protected $header = [];

    //返回参数
    protected $result = [];

    //请求类型
    public function setType($type){
        $this->type = $type;
    }

    //请求url
    public function setUrl($url){
        $this->url = $url;
    }

    //请求参数
    public function setData($data){
        $this->data = $data;
    }

    //添加header参数
    public function setHeader($header){
        foreach ($header as $val){
            $this->header[] = $val;
        }
    }

    //重设header
    public function rebuildHeader($header){
        $this->header[] = $header;
    }

    //请求
    public function sendRequest(){
        if($this->type == "POST"){
            $this->sendPost();
        }else{
            $this->sendGet();
        }
        return $this->result;
    }

    //GET请求
    protected function sendGet(){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $this->url);
        //设置头文件的信息作为数据流输出
        //curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        $this->result = $data;
    }

    //POST请求
    protected function sendPost(){
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $this->url);
        //设置头文件的信息作为数据流输出
        //curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        $this->result = $data;
    }
}